﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PdfLibrary
{
    public interface IPdfObject
    {
        bool LoadFromReader(PdfReader reader, bool throwException);

        /*public void LoadFromReader(PdfReader reader)
        {
            this.LoadFromReader(reader, true);
        }*/
    }

    public static class PdfObject
    {
        public static T CreateFromReader<T>(PdfReader reader) where T : IPdfObject
        {
            Type type = typeof(T);

            IPdfObject tmpObj = SingletonDictionary.Get<T>();

            int originalPosition = reader.Position;

            if (tmpObj.LoadFromReader(reader, false))
            {
                SingletonDictionary.Reset<T>();
                return (T)tmpObj;
            }
            else
            {
                reader.Position = originalPosition;
                return default(T);
            }
        }

        public static IPdfObject CreateFromReader(PdfReader reader, bool readCommands = false)
        {
            IPdfObject result = null;

            if ((result = CreateFromReader<PdfName>(reader)) != null) { }
            else if ((result = CreateFromReader<PdfIndirectReference>(reader)) != null)
            {
                var pdfRef = (PdfIndirectReference)result;
                pdfRef.referenceResolver = reader.File;
            }
            else if ((result = CreateFromReader<PdfNumber>(reader)) != null) { }
            else if ((result = CreateFromReader<PdfBoolean>(reader)) != null) { }
            else if ((result = CreateFromReader<PdfArray>(reader)) != null) { }
            else if ((result = CreateFromReader<PdfDictionary>(reader)) != null)
            {
                var tmpDict = (PdfDictionary)result;

                SingletonDictionary.Get<PdfStream>().dictionary = tmpDict;
                if ((result = CreateFromReader<PdfStream>(reader)) == null)
                    result = tmpDict;
            }
            else if ((result = CreateFromReader<PdfString>(reader)) != null) { }
            else if ((result = CreateFromReader<PdfNull>(reader)) != null) { }
            else if (readCommands && (result = CreateFromReader<PdfCommand>(reader)) != null) { }

            if (result == null)
                throw new PdfParsingException(reader, "Unknown PdfObject!");

            return result;
        }
    }
}
